/**
 * 基于wx的小程序网络请求封装类
 *
 */
import Tips from './tips';
import { cryptoToken, auth } from '../utils/auth';

export default class WXRequest {
  /**
   * 网络请求的前置逻辑，获取token
   */
  static async beforeAction() {
    let accessToken = wx.getStorageSync('accessToken');
    if (!accessToken) {
      console.log('没有token的情况');
      const token = await auth();
      return Promise.resolve(token);
    }

    return Promise.resolve(accessToken);
  }

  static async request(method, url, data, loading = true, needTip = true) {
    const accessToken = await this.beforeAction();
    if (loading) {
      Tips.navLoading();
    }

    let reqURL = url;
    return new Promise((resolve, reject) => {
      wx.request({
        url: reqURL,
        method: method || 'GET',
        data: data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + cryptoToken(accessToken)
        },
        success: (res) => {
          console.log('response: ', res);
          Tips.loaded();
          if (res.statusCode >= 200 && res.statusCode < 400) {
            if (res.data.code === 200) {
              return resolve(res.data);
            }
          }

          if (res.statusCode === 401) {
            console.log('重新请求');
            auth();
          }

          let error = {};
          if (res.data.code) {
            error.statusCode = res.statusCode;
            error.code = res.data.code;
            error.errMsg = res.data.msg;
          } else {
            error.errMsg = res.data.error;
          }
          if (needTip) {
            Tips.error(error.errMsg);
          }
          return reject(error);
        },
        fail: (errObj) => {
          let error = {};
          error.statusCode = 500;
          error.code = 500;
          error.errMsg = errObj.errMsg;
          if (needTip) {
            Tips.error(error.errMsg);
          }
          return reject(error);
        }
      });
    });
  }

  static get(url, data, loading = true) {
    return this.request('GET', url, data, loading, true);
  }

  static post(url, data, loading = true) {
    return this.request('POST', url, data, loading, true);
  }

  static put(url, data, loading = true) {
    return this.request('PUT', url, data, loading);
  }

  static patch(url, data, loading = true) {
    return this.request('FETCH', url, data, loading);
  }

  static delete(url, data, loading = true) {
    return this.request('DELETE', url, data, loading);
  }
}
